import json
from pymongo import MongoClient
from django.core.management.base import BaseCommand
from django.conf import settings
from backend.eform.models import EformSchema
from datetime import datetime

class Command(BaseCommand):
    help = 'Restores JSON backup data into MongoDB using pymongo.'

    def add_arguments(self, parser):
        parser.add_argument('file_path', nargs='?',type=str, help='Path to the JSON backup file',default='backend/eform/data/eform_eformschema_iosystem.json')

    def handle(self, *args, **options):
        ## check eformscheam len
        if EformSchema.objects.all().count() > 0:
            self.stdout.write(self.style.ERROR('EformSchema is not empty.'))
            return
        
        file_path = options['file_path']
        self.stdout.write(f'Restoring data from file: {file_path}')

        # Connect to MongoDB using djongo settings
        mongo_settings = settings.DATABASES['mongo']
        client = MongoClient(
            host=mongo_settings['CLIENT']['host'],
            port=mongo_settings['CLIENT']['port'],
            username=mongo_settings['CLIENT']['USERNAME'],
            password=mongo_settings['CLIENT']['PASSWORD'],
        )

        # Specify the target database and collection
        db_name = mongo_settings['NAME']
        collection_name = 'eform_eformschema'  # Replace with your target collection name
        db = client[db_name]
        collection = db[collection_name]
        def custom_object_hook(obj):
            if "$date" in obj:
                return datetime.fromisoformat(obj["$date"])
            return obj

        with open(file_path, 'r') as f:
            data = json.load(f, object_hook=custom_object_hook)

        clean_data = []
        for item in data:
            if '_id' in item:
                del item['_id']
            clean_data.append(item)

        # Insert the data into the collection
        result = collection.insert_many(clean_data)


        self.stdout.write(self.style.SUCCESS('Data restored successfully.'))
